package com.youease.chris
{
	import com.youease.chris.action.BaseAction;
	import com.youease.chris.event.ActionEvent;
	import com.youease.chris.event.TickEvent;
	import com.youease.chris.util.Tick;

	public class ActionQueue extends BaseAction
	{
		private var _delay:int = 0;
		private var currentTime:int = 0;
		private var actions:Array;
		private var currentAction:BaseAction;
		
		/**
		 * @param actions 队列数据
		 * @param delay 延迟(秒)
		 */ 
		public function ActionQueue(actions:Array,delay:Number=0)
		{
			this.actions = actions;
			this._delay = delay*1000;
		}
		
		override public function execute():void {
			super.execute();
			if(this._delay>0) {
				Tick.instance.addEventListener(TickEvent.TICK,tickHandler);
			}
			executeAction();
		}
		
		private function executeAction():void {
			if(actions && actions.length>0) {
				currentAction = actions[0];
				currentAction.addEventListener(ActionEvent.ACTION_COMPLETE,nextAction);
				currentAction.execute();
			}else {
				complete();
			}
		}
		
		private function nextAction(evt:ActionEvent=null):void {
			var action:BaseAction = actions[0] as BaseAction;
			action.removeEventListener(ActionEvent.ACTION_COMPLETE,nextAction);
			
			actions.shift();
			
			if (evt && evt.type == ActionEvent.ACTION_COMPLETE)
				executeAction();
		}
		
		private function tickHandler(evt:TickEvent):void {
			currentTime += evt.interval;
			if(currentTime >= this._delay) {
				this.dispatchEvent(new ActionEvent(ActionEvent.ACTION_COMPLETE));
				Tick.instance.removeEventListener(TickEvent.TICK,tickHandler);
			}
		}
		
		public function get delay():Number {
			return this._delay;
		}
		
		public function set delay(d:Number):void {
			this._delay = d;
		}
		
	}
}